import { reactive } from "vue"
import { getChatList, getChatSender } from "../api/chat/chat";
import { getUserInfo } from "../api/user/user";
import {  ChatItemRedisType, InitChatInfo, InitSender, SenderInfoType } from "../type/chat";
import { userInfoByBack } from "../type/user";

const chatStore={
	senderList :reactive(
	new Array<SenderInfoType>() 
	),
	//添加聊天对象
	addSender(senderInfo : SenderInfoType){
		chatStore.senderList.push(senderInfo);
		uni.setStorageSync('senderList',chatStore.senderList);
	},
	delSender(senderId:string){
		for (var i = 0; i < chatStore.senderList.length; i++) {
				if(chatStore.senderList[i].senderId ===senderId){
					//去除聊天的列表记录
					chatStore.senderList.splice(i,1);
					uni.setStorageSync('senderList',chatStore.senderList);
					//去除聊天内容记录
					uni.removeStorageSync(senderId);
					return;
				}
		}
	},
	//判定消息列表是否存在该发送用户
	isExistSender(senderId:string):boolean{
		var flag=0;
		while (flag < chatStore.senderList.length) {
		     if(chatStore.senderList[flag].senderId===senderId){
					   return true;
				   }
				   flag++;
			}
		return false;
	},
	//初始登录 获取保存在redis的未读消息
	initRedisChatList(userId:string){
		//获取到发送者 列表
		getChatSender(userId).then((res:Set<string>)=>{
			//判定聊天列表是否存在该发送用户 未存在 需添加
			if(res!=null){
			  res.forEach(itemId=>{
			  	if (!chatStore.isExistSender(itemId)) {
			  		getUserInfo(itemId).then((res: userInfoByBack) => {
			  			var senderInfo = reactive(new InitSender());
			  			senderInfo.senderId = itemId;
			  			senderInfo.senderImg = res.userImg;
			  			senderInfo.senderName = res.username;
			  			chatStore.addSender(senderInfo);
			  		});
			  	}
			  })	
			}
		})
		//获取到发送消息
		getChatList(userId).then((res:Array<ChatItemRedisType>)=>{			
			if(res !==null){
			  res.forEach(item => {
			  	var chatInfo = new InitChatInfo();
			  	chatInfo.sendUser = 1;
			  	chatInfo.sendMessage = item.text;
			  	var list: Array<InitChatInfo> = [...uni.getStorageSync(item.fromUserId)];
			  	list.push(chatInfo);
			  	uni.setStorageSync(item.fromUserId, list);
			  	var unreadNum: number = uni.getStorageSync('unRead' + item.fromUserId);
			  	unreadNum++;
			  	uni.setStorageSync('unRead' + item.fromUserId, unreadNum);
			  	uni.setStorageSync('sendTime' + item.fromUserId, item.dateTime);
			  });
			}
		})
	}
}


export default chatStore